#include "Common.h"
#include "Material.h"
#include "MaterialInstance.h"
#include "Shader.h"

Material::Material(const std::string& name)
	: mName(name)
	, mTransparent(false)
	, mMasked(false)
	, mDefaultInstance(NULL)
	, mDefine(NULL)
{
}

Material::~Material()
{
	SAFE_DELETE(mDefaultInstance);
}

void Material::Define(ShaderDefineMap* defineMap)
{
	if (mDefine != NULL)
		mDefine(defineMap);
}

void Material::Compile()
{
	mShaderMap.Compile(this);

	SAFE_DELETE(mDefaultInstance);
	mDefaultInstance = new MaterialInstance(this);
}

void Material::BuildParamRef(const Shader* shader, MaterialParameterRefList& refList) const
{
	// build material param ref.
	Shader::ParamsIterator it = shader->GetParamIterator();
	while (it.hasMoreElements())
	{
		MaterialParameterRef ref = mMaterialParameter.GetParamRef(it.peekNextKey());
		if (ref.Valid())
		{
			ref.Register = ShaderParameter(it.peekNextValue());
			refList.push_back(ref);
		}

		it.moveNext();
	}
}

MaterialInstance* Material::CreateInstance() const
{
	return new MaterialInstance(this);
}